import { type ActionType, FooterToolbar, PageContainer, type ProColumns, ProDescriptions, type ProDescriptionsItemProps, ProTable, } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, message, Tag } from 'antd';
import React, { useCallback, useRef, useState } from 'react';
import { getCustomer } from '@/apis/customer';
import type { CustomerInfo } from '@/pages/customer/index.data';
import { removeRule } from '@/services/ant-design-pro/api';
import CreateForm, { type CreateFormRef, } from './components/CreateForm/CreateForm';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType | null>(null);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<any>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const [messageApi, contextHolder] = message.useMessage();

  const {run: delRun, loading} = useRequest(removeRule, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();

      messageApi.success('删除成功');
    },
    onError: () => {
      messageApi.error('删除失败，请重试');
    },
  });

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async ( selectedRows: API.RuleListItem[] ) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');

        return;
      }
    },
    [delRun, messageApi.warning],
  );

  const handleDelete = useCallback(async ( record: any ) => {
    const res = await delRun(record.id);
  }, []);

  const createRef = useRef<CreateFormRef>(null);
  const handleEdit = ( record: CustomerInfo ) => {
    if (createRef.current) {
      createRef.current.handleEdit(record.id);
    }
  };

  // 表格列配置 - 使用小驼峰命名法
  const columns: ProColumns<CustomerInfo>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
      hideInSearch: true,
      hideInTable: true,
    },

    {
      title: '客户全称',
      dataIndex: 'customerFullName',
      key: 'customerFullName',
      width: 150,
      ellipsis: true,
      search: {
        transform: ( value: string ) => ({customerFullName: value}),
      },
      formItemProps: {
        rules: [{required: true, message: '客户全称为必填项'}],
      },
    },
    {
      title: '客户简称',
      dataIndex: 'customerShortName',
      key: 'customerShortName',
      width: 100,
      ellipsis: true,
      formItemProps: {},
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '速记码',
      dataIndex: 'shorthandCode',
      key: 'shorthandCode',
      width: 80,
    },
    {
      title: '是否同行',
      dataIndex: 'isPeer',
      key: 'isPeer',
      width: 80,
      render: ( _, record ) => (
        <Tag color={record.isPeer ? 'blue' : 'default'}>
          {record.isPeer ? '是' : '否'}
        </Tag>
      ),
      valueType: 'select',
      valueEnum: {
        true: {text: '是'},
        false: {text: '否'},
      },
    },
    {
      title: '所属地区',
      dataIndex: 'region',
      key: 'region',
      width: 100,
    },
    {
      title: '业务员',
      dataIndex: 'salesman',
      key: 'salesman',
      width: 80,
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
      key: 'contactPhone',
      width: 120,
    },
    {
      title: '手机号码',
      dataIndex: 'mobilePhone',
      key: 'mobilePhone',
      width: 120,
    },
    {
      title: '是否需要开票',
      dataIndex: 'needInvoice',
      key: 'needInvoice',
      width: 100,
      render: ( _, record ) => (
        <Tag color={record.needInvoice ? 'green' : 'red'}>
          {record.needInvoice ? '需要' : '不需要'}
        </Tag>
      ),
      valueType: 'select',
      valueEnum: {
        true: {text: '需要'},
        false: {text: '不需要'},
      },
    },
    {
      title: '成本税率',
      dataIndex: 'costTaxRate',
      key: 'costTaxRate',
      width: 80,
      render: ( _, record ) => `${record.costTaxRate}%`,
    },
    {
      title: '应收税率',
      dataIndex: 'receivableTaxRate',
      key: 'receivableTaxRate',
      width: 80,
      render: ( _, record ) => `${record.receivableTaxRate}%`,
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: 150,
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updatedTime',
      key: 'updatedTime',
      width: 150,
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建人',
      dataIndex: 'createdBy',
      key: 'createdBy',
      width: 80,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'deleted',
      key: 'deleted',
      width: 80,
      render: ( _, record ) => (
        <Tag color={record.deleted ? 'red' : 'green'}>
          {record.deleted ? '已删除' : '正常'}
        </Tag>
      ),
      valueType: 'select',
      valueEnum: {
        false: {text: '正常', status: 'Success'},
        true: {text: '已删除', status: 'Error'},
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: ( text, record, _, action ) => [
        <a
          key="editable"
          onClick={() => {
            createRef.current?.handleEdit(record.id);
          }}
        >
          编辑
        </a>,
        <a key="delete" onClick={() => handleDelete(record)}>
          删除
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<CustomerInfo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        tableLayout={'auto'}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() =>
          [<CreateForm
            key="create"
            ref={createRef}
            reload={actionRef.current?.reload}
          />]
        }
        request={getCustomer}
        columns={columns}
        rowSelection={{
          onChange: ( _, selectedRows ) => {
            setSelectedRows(selectedRows);
          },
        }}
        scroll={{x: 2000, y: 400}}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage
                id="pages.searchTable.chosen"
                defaultMessage="Chosen"
              />{' '}
              <a style={{fontWeight: 600}}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage
                id="pages.searchTable.item"
                defaultMessage="项"
              />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce(
                  ( pre: any, item: { callNo: any } ) => pre + (item.callNo ?? 0),
                  0,
                )}{' '}
                <FormattedMessage
                  id="pages.searchTable.tenThousand"
                  defaultMessage="万"
                />
              </span>
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
